﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Ext.Net;

namespace EVegetable.WebAdmin
{
    using EVegetable.Common.Model;
    using EVegetable.Common.Security;

    using EVegetable.Common.Web;

    using EVegetable.Domain;
    using EVegetable.Service;

    public partial class Login : BaseWebPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {

#if DEBUG
            if (!IsPostBack)
            {
                txtUserName.Text = "administrator";
                txtPassword.Text = "1";
                txtCompanyID.Text = "001";
            }
#endif
        }

        protected void btnSubmit_Click(object sender, DirectEventArgs e)
        {
            this.ValidatePage();

            if (this.ValidObj.IsValid == false)
            {
                X.MessageBox.Alert("温馨提示", this.ValidObj.Message).Show();
                return;
            }
            // Execute the Login Method.
            string loginMessage = DoLogin();
            if (!string.IsNullOrEmpty(loginMessage))
            {
                X.MessageBox.Alert("温馨提示", loginMessage).Show();
                return;
            }

        }

        protected override void ValidatePage()
        {
            base.ValidatePage();

            if (string.IsNullOrEmpty(txtUserName.Text.Trim()))
            {
                this.ValidObj.Message = "请输入用户名！";

                return;
            }
            else if (string.IsNullOrEmpty(txtPassword.Text.Trim()))
            {
                this.ValidObj.Message = "请输入密码！";

                return;
            }
            else if (string.IsNullOrEmpty(txtCompanyID.Text.Trim()))
            {
                this.ValidObj.Message = "请输入公司ID！";

                return;
            }

            this.ValidObj.IsValid = true;
        }

        private string DoLogin()
        {
            string strMessage = string.Empty;
            string strUserID = txtUserName.Text.Trim();
            string strPWD = Cryptographer.EncryptorAESToString(txtPassword.Text.Trim());

            TSys_UserSvc sysUserSvc = new TSys_UserSvc();

            TSys_User paraUser = new TSys_User() { Account = strUserID, PWD = strPWD };
            TSys_User user = sysUserSvc.GetUserByAccountAndPWD(paraUser);
            if (user != null)
            {// Login
                if (user.Active)
                {
                    // Set Login User

                    this.Redirect("Main.aspx");
                }
                else
                {
                    strMessage = "该用户名还未激活！";
                }
            }
            else
            {
                strMessage = "用户名或密码不正确！";
            }

            return strMessage;
        }
    }
}
